package com.study.talk.common.security;

import com.alibaba.druid.util.StringUtils;
import com.study.talk.common.util.JwtUtil;
import com.study.talk.common.util.RedisUtils;
import com.study.talk.common.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.AccessControlException;
import java.util.Map;

@Component
@Slf4j
public class SimpleTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        String userName = "游客";
        if (!StringUtils.isEmpty(authorization)){
            if (redisUtils.hasKey(authorization)) {
                try {
                    Map body = JwtUtil.getBody(authorization);
                     userName = (String) body.get("userName");
                    Authentication authentication = null;
                    authentication=tokenUtil.getTokenAuthentication(userName);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }catch (Exception e){
                    request.setAttribute("errCode",401);
                    request.setAttribute("errorMsg","token错误或者失效,请重新登录后再试");
                    throw new AccessControlException("token失效");
                }
            }else {
                request.setAttribute("errCode",401);
                request.setAttribute("errorMsg","token失效,请重新登录后再试");
                throw new AccessControlException("token失效");
            }
        }
//        String ipAddr = IpUtils.getIpAddr(request);
//        String logInfo = String.format("用户:%s    正在访问接口:%s     请求ip：%s     真实地址:%s ",userName,request.getRequestURI(), ipAddr, AddressUtils.getRealAddressByIP(ipAddr));
//        log.info(logInfo);
//        redisUtils.lSet("logInfo",logInfo);
        filterChain.doFilter(request,response);
    }
}
